<template>
  <div>
    <TopFilter :list="topFilterList" :cols="4" @filterChange="changeHandler" @onCollapse="collapseHandle" />
    <FilterTable
      ref="table"
      columnsRef="jzyCardType"
      :columns="columns"
      :fetchapi="fetchApi"
      :params="fetchParams"
      :datakey="'rows'"
      :isSelectColumn="false"
      :onRowSelectChange="rowSelectHandle"
      :onColumnsChange="columns => (this.columns = columns)"
      :isExportExcel="true"
      :onCalcExportData="exportFun"
      exportFileName="打印销售发票.xlsx"
    >
      <!-- <template slot="moreActions">
        <span @click="removeRecordHandle">删除数据</span>
      </template> -->
      <template slot="controls">
        <el-button size="small" type="primary" icon="el-icon-printer" @click="handlePrint">打印</el-button>
        <!-- <el-button size="small" type="primary" icon="el-icon-download">导出</el-button> -->
      </template>
    </FilterTable>
    <!-- 打印 -->
    <div v-if="dy">
      <BasePrint ref="print" :data="printData" template="templatePartSaleOrder" />
    </div>
  </div>
</template>

<script>
// 数据字典/按钮权限
import { dictionary } from '@/utils/dictMixin';
import { jsonToHump } from '@/utils/index';
import { getPartInvoiceList, getPartInvoicePrintData } from '@/api/part/report/printPartInvoice';
import { getStroageList } from '@/api/part/partOutbound/partBreak';
import moment from 'moment';
export default {
  name: 'CardType',
  components: {},
  mixins: [dictionary],
  data() {
    this.BaseTable = null;
    this.selectedRow = null;
    this.editData = {};
    return {
      topFilterList: this.createTopFilters(),
      columns: this.createTableColumns(),
      fetchApi: getPartInvoiceList,
      fetchParams: {},
      searchData: {},
      dy: false,
      printData: {},
      actions: { visible: false, type: '', title: '' } // 弹出面板的相关信息
    };
  },
  // created() {
  //   this.getStorage();
  // },
  mounted() {
    this.BaseTable = this.$refs.table.$refs.pageTable;
  },
  methods: {
    exportFun(row) {
      for (const key in row) {
        switch (key) {
          case 'sheetCreatedDate':
            if (row[key]) {
              row[key] = moment(row[key]).format('YYYY-MM-DD');
            }
            break;
          case 'CONSULTANT':
            if (row[key]) {
              // row[key] = this.userList[row[key]];
            }
            break;
          case 'STOCK_QUANTITY':
          case 'OUT_PRICE':
          case 'COST_PRICE':
          case 'OUT_AMOUNT':
          case 'COST_AMOUNT':
          case 'VOLUME':
            if (row[key]) {
              row[key] = Number(row[key]).toFixed(2);
            }
            break;
          default:
            break;
        }
      }
    },
    createTopFilters() {
      return [
        {
          type: 'INPUT',
          label: '发票类型',
          fieldName: 'FKART',
          placeholder: '请输入...'
        },
        {
          type: 'SELECT',
          label: '成品油分类',
          fieldName: 'OIL_TYP',
          placeholder: '请选择...',
          itemList: [
            { value: 10451001, text: '成品油' },
            { value: 10451003, text: '非成品油' }
          ]
        },
        {
          type: 'INPUT',
          label: '发票号',
          fieldName: 'VBELN',
          placeholder: '请输入...'
        },
        {
          type: 'RANGE_DATE',
          label: '发票日期',
          fieldName: 'BERDAT_START|BERDAT_END',
          rules: [{ required: true, message: '选择日期', trigger: 'blur' }]
        }
      ];
    },
    createTableColumns() {
      return [
        {
          title: '序号',
          dataIndex: 'index',
          width: 70,
          sorter: true,
          render: props => {
            return <span>{props.row.index + 1}</span>;
          }
        },
        {
          title: '经销商代码',
          dataIndex: 'KUNRG',
          sorter: true,
          filter: true,
          filterType: 'input'
        },
        {
          title: '经销商名称',
          width: 150,
          dataIndex: 'NAME1',
          sorter: true,
          filter: true,
          filterType: 'input',
          showOverflowTooltip: true
        },
        {
          title: '服务站代码',
          dataIndex: 'KUNNR',
          sorter: true,
          filter: true,
          filterType: 'input'
        },
        {
          title: '发票号',
          dataIndex: 'VBELN',
          sorter: true,
          filter: true,
          filterType: 'input'
        },
        {
          title: '发票类型',
          dataIndex: 'FKART',
          sorter: true,
          filter: true,
          filterType: 'input'
        },
        {
          title: '发票日期',
          dataIndex: 'BERDAT',
          sorter: true,
          filter: true,
          filterType: 'input'
        },
        {
          title: '税号',
          dataIndex: 'STCD1',
          sorter: true,
          filter: true,
          width: 150,
          showOverflowTooltip: true,
          filterType: 'input'
        },
        {
          title: '配件代码',
          dataIndex: 'MATNR',
          sorter: true,
          filter: true,
          filterType: 'input',
          width: 150,
          showOverflowTooltip: true
        },
        {
          title: '配件名称',
          dataIndex: 'PART_DESCRIPTION',
          sorter: true,
          filter: true,
          filterType: 'input',
          width: 150,
          showOverflowTooltip: true
        },
        {
          title: '成品油分类',
          dataIndex: 'OIL_TYP',
          sorter: true,
          filter: true,
          filterType: 'input'
        },
        {
          title: '原数量',
          dataIndex: 'FKIMG',
          sorter: true,
          filter: true,
          filterType: 'number'
        },
        {
          title: '体积（L）',
          dataIndex: 'VOLUME',
          sorter: true,
          filter: true,
          precision: 2,
          filterType: 'number'
        },
        {
          title: '单价',
          dataIndex: 'PRICE',
          sorter: true,
          filter: true,
          precision: 2,
          filterType: 'number'
        },
        {
          title: '金额',
          dataIndex: 'NETWR',
          sorter: true,
          filter: true,
          filterType: 'number'
        },
        {
          title: '税率',
          dataIndex: 'TAX_RATE',
          sorter: true,
          filter: true,
          filterType: 'number'
        },
        {
          title: '税额',
          dataIndex: 'MWSBK',
          sorter: true,
          filter: true,
          precision: 2,
          filterType: 'number'
        }
      ];
    },
    async getStorage() {
      const res = await getStroageList();
      this.topFilterList.find(item => item.fieldName === 'STORAGE_CODE').itemList = res.data.map(x => ({ text: x.STORAGE_NAME, value: x.STORAGE_CODE }));
    },
    // 打印的方法
    async handlePrint() {
      // // 打印数据
      const res = await getPartInvoicePrintData(this.searchData);
      let data = _.cloneDeep(res.data);
      for (const item of data.invoice) {
        let amount = 0; // 金额
        let taxAmount = 0; // 税额
        // let priceTax = 0 // 价税
        for (const obj of item.items) {
          amount += Number(obj.netwr);
          taxAmount += Number(obj.mwsbk);
        }
        item.amount = amount.toFixed(2);
        item.taxAmount = taxAmount.toFixed(2);
        item.priceTax = (amount + taxAmount).toFixed(2);
      }
      this.printData = data;
      console.log(this.printData, 'printData');
      this.dy = true;
      // 打印
      this.$nextTick(() => {
        this.$refs.print.EXCUTE_PRINT();
      });
    },
    addRecordHandle() {
      this.actions = { visible: true, type: 'add', title: '新增会员卡信息' };
    },
    editRecordHandle(row) {
      if (!row) return;
      this.editData = row;
      this.actions = { visible: true, type: 'edit', title: '编辑会员卡信息' };
    },
    changeHandler(val) {
      console.log(val, 'val');
      this.searchData = val;
      if (val['BERDAT_START|BERDAT_END'].length > 0) {
        this.searchData.DATE_RANGE = val.BERDAT_START.slice(0, 10) + '——' + val.BERDAT_END.slice(0, 10);
        // this.searchData.DATE_RANGE_BEGIN = val.BERDAT_START.slice(0, 10);
        // this.searchData.DATE_RANGE_END = val.BERDAT_END.slice(0, 10);
      }
      console.log(this.searchData, 'searchData');
      this.fetchParams = { ...val };
    },
    rowSelectHandle(rows) {
      if (!rows.length) return;
      this.selectedRow = rows[0];
    },

    // 主页面刷新
    refreshHandle() {
      this.fetchParams = { ...this.fetchParams };
    },

    // 适配 BaseTable 组件
    collapseHandle() {
      this.$nextTick(this.BaseTable.EXECUTE_RESET_HEIGHT);
    }
  }
};
</script>

<style lang="less" scoped></style>
